﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Entity;
using Kelper.Domain.Models;
using Kelper.Domain.Data.Abstract;

namespace Kelper.Domain.Data
{
    public class IngredientRepository : IIngredientRepository
    {
        private KelperDbContext db;

        public IngredientRepository(KelperDbContext db)
        {
            this.db = db;
        }

        public IQueryable<Ingredient> Ingredients
        {
            get { return db.Ingredients; }
        }

        /*
         * This is basically what I am trying to accomplish
         * 
         * SELECT Ingredients.Name, COUNT(RecipeIngredients.Name) AS UsageCount
         * FROM Ingredients INNER JOIN
         *     RecipeIngredients ON Ingredients.Name = RecipeIngredients.Name
         * GROUP BY Ingredients.Name
         * ORDER BY UsageCount DESC
         */
        public IEnumerable<Ingredient> GetMostPopular(int max)
        {
            return GetMostPopularWithCount(max).Select(i => i.Key);
        }

        public IEnumerable<KeyValuePair<Ingredient, int>> GetMostPopularWithCount(int max)
        {
            return db.Recipes
                .SelectMany(r => r.Ingredients)     // This is a nice way to get a join table
                .GroupBy(i => i)
                .Select(g => new
                {
                    Ingredient = g.Key,
                    Count = g.Count()
                })
                .OrderByDescending(t => t.Count)
                .Take(max)
                .ToList()       // Fetch entries from db
                .Select(i => new KeyValuePair<Ingredient, int>(i.Ingredient, i.Count));
        }
    }
}
